﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using Ufida.T.EAP.Net;
using Newtonsoft;
using Newtonsoft.Json;

namespace Chanjet.TP.OpenAPI.Demo
{
	public partial class Form1 : Form
	{
        private DB_class db = new DB_class();
        
		public Form1()
		{
			InitializeComponent();
		}

        Chanjet.TP.OpenAPI.OpenAPI TPlusAPI = null;

		Args demoArgs = new Args();

		string curResource_Method { get; set; }



		private void CreateDoc()
		{
			OpenAPI api = new OpenAPI("http://127.0.0.1/TPlus/api/v1/", new Credentials()
			{
				AppKey = "myAppKey",
				AppSecret = "myAppSecret",
				UserName = "demo",
				Password = "",
				AccountNumber = "1",
				LoginDate = DateTime.Now.ToString("yyyy-MM-dd")
			});                                            //创建OpenAPI的调用对象(传入服务地址，及认证信息)

			api.GetToken();                        //申请访问授权

			api.Call("doc/Create",                    //调用凭证的创建服务
			@"{  
        dto: {
            ExternalCode:""002"",
            DocType: { Code: ""记"" }, 
            VoucherDate: """ + DateTime.Now.ToString("yyyy-MM-dd") + @""",
            Entrys: [
                { 
                    Account: { ""Code"": ""1001"" },
                    Currency: { ""Code"": ""RMB"" },
                    Summary: ""提现"", AmountCr: ""100""
                }
                , { 
                    Account: { ""Code"": ""1002"" },
                    Currency: { ""Code"": ""RMB"" },
                    Summary: ""提现"", AmountDr: ""100""
                }]
        }
    }");

			api.Call("inventory/Query", "{param:{Code:\"001\"}}");
			api.Call("", "");

		}








		private void btnConnectTest_Click(object sender, EventArgs e)
		{
            /*
			Credentials credentials = new Credentials()
			{
				AppKey = txtAppKey.Text,
				AppSecret = txtAppSecret.Text
			};

			string host = "127.0.0.1", uri = "TPlus/api/v1/rest/Connect";
			string ApiUrl = string.Format("http://{0}/{1}", host, uri);
			WebClient wc = new WebClient();
			wc.Headers["Authorization"] = credentials.Signature(ApiUrl, string.Format("{0:R}", DateTime.Now));
			string returnValue = wc.DownloadString(ApiUrl);

			txtLog.AppendText("\r\n Call:ConnectTest \r\n result:" + returnValue);

			return;
			 */

            string testConnStr = cmServerURL.Text;
            if (testConnStr.Contains("api/v2"))
            {
                testConnStr = testConnStr.Replace("api/v2","api/v1");
            }

            OpenAPI api = new OpenAPI(testConnStr, new Credentials()
			{
				AppKey = txtAppKey.Text,
				AppSecret = txtAppSecret.Text
			});

			try
			{
				dynamic r = api.ConnectTest();

				txtLog.AppendText("\r\n Call:Connection \r\n result:" + r.status + "\r\n" + r.ToString());
			}
			catch (RestException ex)
			{
                if (ex==null || ex.Response==null)
                {
                    txtLog.AppendText("请求地址错误！"  );
                }
                else
                {
                    txtLog.AppendText("\r\n Call:Connection \r\n error:" + ex.Response.StatusCode + "  " + ex.Message + "\r\n" + ex.ResponseBody);
                }				
			}
		}


		private void btnReLogin_Click(object sender, EventArgs e)
		{
			try
			{
				dynamic r = this.TPlusAPI.ReLogin();

				txtLog.AppendText("\r\n Call:btnReLogin_Click \r\n result:" + r.access_token + "\r\n" + r.ToString());
			}
			catch (RestException ex)
			{
				txtLog.AppendText("\r\n Call:btnReLogin_Click \r\n error:" + ex.Response.StatusCode + "  " + ex.Message + "\r\n" + ex.ResponseBody);
			}

		}


		private void btnGetToken_Click(object sender, EventArgs e)
		{
            string strServerUrl = cmServerURL.Text;
            if (cmServerURL.Text.Contains("api/v2"))
            {
                strServerUrl = strServerUrl.Replace("api/v2","api/v1");
                cmServerURL.Text = strServerUrl;
            }

            this.TPlusAPI = new OpenAPI(strServerUrl, new Credentials()
			{
				AppKey = txtAppKey.Text,
				AppSecret = txtAppSecret.Text,
				UserName = txtUserName.Text,
				Password = txtPassWord.Text,
				LoginDate = txtLoginDate.Text,
				AccountNumber = txtAccountNum.Text
			});

			try
			{
				dynamic r = r = TPlusAPI.GetToken();
				Console.Write((string)r.access_token);
				txtLog.AppendText("\r\n Call:btnGetToken_Click \r\n result:" + r.access_token + "\r\n" + r.ToString());
			}
			catch (RestException ex)
			{
				txtLog.AppendText("\r\n Call:btnGetToken_Click \r\n error:" + ex.Response.StatusCode + "  " + ex.Code + "  " + ex.Data + "  " + ex.Message + "\r\n" + ex.ResponseBody);
                if (ex.Code == "EXSM0004")
                {
                    this.btnReLogin_Click(sender, e);
                }
                else if (ex.Code == "EXSM0003")
                {
                    this.btnReLogin_Click(sender, e);
                }
                else if (ex.Code == "EXSM0005")
                {
                    this.btnReLogin_Click(sender, e);
                }
                else
                {
                    this.btnReLogin_Click(sender, e);
                }
            }

		}


		private void btnLogout_Click(object sender, EventArgs e)
		{
			try
			{
				dynamic r = TPlusAPI.Logout();
				txtLog.AppendText("\r\n Call:Logout \r\n result:" + r);
			}
			catch (RestException ex)
			{
				txtLog.AppendText("\r\n Call:Logout \r\n error:" + ex.Message + "\r\n" + ex.ResponseBody);
			}
		}

		bool isLogined()
		{
			if (TPlusAPI != null && !string.IsNullOrEmpty(TPlusAPI.Credentials.Access_Token))
				return true;
			return false;
		}


		#region UIController
		private void cbEncoder_CheckedChanged(object sender, EventArgs e)
		{
			string apiValue = txtArgs.Text;

			if (cbEncoder.Checked)
			{
				if (apiValue.StartsWith("{"))
				{
					apiValue = HttpUtility.UrlEncode(apiValue, Encoding.UTF8);
				}
			}
			else
			{
				if (!apiValue.StartsWith("{"))
				{
					apiValue = HttpUtility.UrlDecode(apiValue, Encoding.UTF8);
				}

			}

			txtArgs.Text = apiValue;

		}


		private void Form1_Load(object sender, EventArgs e)
		{
			txtLoginDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
        }
		#endregion


		string[] restResourceMethod = new string[] { 
        ""
        ,"inventory/Query"
        ,"brand/Query"
        ,"freeItemType/Query"
        ,"freeItem/Query"
        ,"warehouse/Query"
        ,"barCode/Query"
        ,"voucherDraft/Query"
        ,""
        ,""
        ,"saleDelivery/Create"
        ,"saleDelivery/CreateBatch"
        ,""
        ,"otherDispatch/Create"
        ,"otherDispatch/CreateBatch"
        ,"currentStock/Query"
        ,"materialDispatch/Create"
        ,"purchaseReceive/Create"
        ,"otherReceive/Create"
        ,"productReceive/Create"
        ,""
        ,""
        ,"doc/Create"
        ,"doc/CreateBatch"
        ,"",
        "productReceive/Create"
        };

		private void lstRestResourceMethod_SelectedIndexChanged(object sender, EventArgs e)
		{ 
			curResource_Method = restResourceMethod[lstRestResourceMethod.SelectedIndex];
            //MessageBox.Show("id:"+lstRestResourceMethod.SelectedIndex);
            //MessageBox.Show(curResource_Method);
            txtResourceName.Text = curResource_Method;
            //MessageBox.Show(txtResourceName.Text);
			if (curResource_Method == "")
			{
				txtArgs.Text = string.Empty;
				return;
			}
			string argFieldName = curResource_Method.Replace("/", "_");
            //MessageBox.Show(argFieldName);
            txtArgs.Text = typeof(Args).GetField(argFieldName).GetValue(demoArgs).ToString();
            //MessageBox.Show("1:"+txtArgs.Text);
            txtArgs.Text = txtArgs.Text.Replace("2014-09-30", DateTime.Now.ToString("yyyy-MM-dd"));
            txtStock.Text = typeof(Args).GetField(argFieldName+"_Text").GetValue(demoArgs).ToString();
        }

		private void btnPOST_Click(object sender, EventArgs e)
		{
            //查看是v1 还是v2
            if (this.cmServerURL.Text.ToLowerInvariant().Contains("v1"))
            {
                if (!isLogined())
                {
                    if (MessageBox.Show("未登录，是否登录？", "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        this.btnGetToken_Click(sender, e);
                    }
                    else
                    {
                        return;
                    }
                }


                try
                {
                    string result = this.TPlusAPI.Call<string>(txtResourceName.Text, txtArgs.Text);

                    //dynamic result = this.TPlusAPI.Call(txtResourceName.Text, txtArgs.Text);

                    txtLog.AppendText("\r\n\r\n call:" + txtResourceName.Text);
                    txtLog.AppendText("\r\n result:" + result);
                }
                catch (RestException ex)
                {
                    txtLog.AppendText("\r\n\r\n call:" + txtResourceName.Text);
                    txtLog.AppendText("\r\n error:" + ex.Message + "\r\n" + ex.ResponseBody);
                }
            }
            else
            {
                //v2
                try {
                    string appkey = this.txtAppKey.Text.Trim();
                    string appsecret = this.txtAppSecret.Text.Trim();
                    string orgid = this.textBoxOrgId.Text.Trim();
                    //业务请求的Authorization
                    var customParas = new Dictionary<string, object>
                {
                    {"access_token", token_v2},

                };
                    //默认规则是当前参数+appsecret，组成签名的原值
                    var bizheader = new Dictionary<string, object>
                {
                    {"appkey", appkey},
                    {"orgid",fromOrgId?orgid:string.Empty},
                    {"appsecret", appsecret}
                };
                    string privateKeyPath = this.txtPriKeyPath.Text.Trim();
                    if (string.IsNullOrEmpty(privateKeyPath) || !File.Exists(privateKeyPath))
                    {
                        MessageBox.Show("请指定私钥路径！");
                    }

                    RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
                    string bizdatas = jsonSerializer.Serialize(bizheader);
                    Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();
                    string bizAuthorization = tokenManage.CreateSignedToken(bizdatas, privateKeyPath, customParas);
                    ITRestRequest restquest1 = new TRestRequest();
                    restquest1.Method = TMethod.POST;
                    string serverUrl = this.cmServerURL.Text.Trim();
                    string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2) + 1);
                    restquest1.Resource = serverUrl.Replace(host, "") + txtResourceName.Text;
                    string authStr1 = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + bizAuthorization + @""",""orgId"":" + (fromOrgId ? orgid : @"""""") + @"}";
                    string encode1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr1));
                    restquest1.AddParameter("Authorization", encode1, TParameterType.HttpHeader);
                    string args = txtArgs.Text;
                    restquest1.AddParameter("_args", args);
                    TRestClient restclient = new TRestClient(host);
                    string responsedata1 = restclient.Execute(restquest1);
                    txtLog.AppendText("\r\n\r\n call:" + txtResourceName.Text);
                    txtLog.AppendText("\r\n result:" + responsedata1);
                }
                catch (Exception ex)
                {
                    txtLog.AppendText("\r\n\r\n call:" + txtResourceName.Text);
                    txtLog.AppendText("\r\n error:" + ex.Message);
                }
            }
        }


		private void btnGET_Click(object sender, EventArgs e)
		{
			if (!isLogined())
			{
				MessageBox.Show("请先登录！");
				return;
			}

		}

		private void lstRestResourceMethod_DoubleClick(object sender, EventArgs e)
		{
			if (txtResourceName.Text != "")
			{
				this.btnPOST_Click(sender, e);
			}
		}

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        
        private string token_v2 = "";
        private DateTime token_date = DateTime.Now;
        private bool fromOrgId = false; 
        private void button1_Click(object sender, EventArgs e)
        {

            // v2 获取token
            string appkey = this.txtAppKey.Text.Trim();
            string appsecret = this.txtAppSecret.Text.Trim();
            string orgid = this.textBoxOrgId.Text.Trim();
            var header = new Dictionary<string, object>
            {
                {"appkey", appkey},
                {"orgid",orgid},//90009444367
                {"appsecret", appsecret}
            };
            RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
            string datas = jsonSerializer.Serialize(header);
            //MessageBox.Show(datas);
            //MessageBox.Show(datas);
            Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();
            string signvalue = tokenManage.CreateSignedToken(datas, @"D:\cjet_pri.pem");
            MessageBox.Show("www:"+signvalue);
            string authStr = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + signvalue + @""",""orgId"":" + orgid + @"}";
            string encode = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr));
            string serverUrl = this.cmServerURL.Text.Trim();
            string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2)+1);
            TRestClient restclient = new TRestClient(host);
            ITRestRequest restquest = new TRestRequest();
            restquest.Resource = serverUrl.Replace(host,"")+ "collaborationapp/GetAnonymousTPlusToken?IsFree=1";
            restquest.AddParameter("Authorization", encode, TParameterType.HttpHeader);
            restquest.Method = TMethod.POST;
            string responsedata = restclient.Execute(restquest);
            Newtonsoft.Json.Linq.JObject token = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(responsedata);
            token_v2 = token["access_token"].ToString();
            token_date = DateTime.Now;
            txtLog.AppendText("\r\n Call:GetTokenV2 \r\n result:" + token_v2 );
            fromOrgId = true;
        }

        private void btnOthFeatures_Click(object sender, EventArgs e)
        {
            OtherFuncForm form = new OtherFuncForm();
            form.Show();
        }
        
        private void btnV2LoginWithUserPwd_Click(object sender, EventArgs e)
        {
            // v2 获取token 用户名 密码
            string appkey = this.txtAppKey.Text.Trim();
            string appsecret = this.txtAppSecret.Text.Trim();
            string userName = this.txtUserName.Text.Trim();
            string pass = this.txtPassWord.Text.Trim();
            string caccNum = this.txtAccountNum.Text.Trim();
            string privateKeyPath = this.txtPriKeyPath.Text.Trim();
            if (string.IsNullOrEmpty(privateKeyPath) || !File.Exists(privateKeyPath))
            {
                MessageBox.Show("请指定私钥路径！");
            }
            var header = new Dictionary<string, object>
            {
                {"appkey", appkey},
                {"orgid",string.Empty},//90009444367
                {"appsecret", appsecret}
            };
            RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
            string datas = jsonSerializer.Serialize(header);
            Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();

           // MessageBox.Show(datas);

            string signvalue = tokenManage.CreateSignedToken(datas, privateKeyPath);

            //MessageBox.Show("ww:"+signvalue);
            string authStr = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + signvalue + @""",""orgId"":""""}";
            string encode = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr));
            string serverUrl = this.cmServerURL.Text.Trim();

            //MessageBox.Show("authStr:"+ authStr);

            if (serverUrl.Contains("api/v1"))
            {
                serverUrl = serverUrl.Replace("api/v1", "api/v2");
                cmServerURL.Text = serverUrl;
            }
            string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2) + 1);
            TRestClient restclient = new TRestClient(host);
            ITRestRequest restquest = new TRestRequest();
            restquest.Resource = serverUrl.Replace(host, "") + "collaborationapp/GetRealNameTPlusToken?IsFree=1";
            restquest.AddParameter("Authorization", encode, TParameterType.HttpHeader);
            pass=this.EncodeMD5(pass);
            string args = string.Format("{{userName:\"{0}\",password:\"{1}\",accNum:\"{2}\"}}", userName, pass,caccNum);
            
            //MessageBox.Show(args);

            restquest.AddParameter("_args", args);
            restquest.Method = TMethod.POST;
            string responsedata = restclient.Execute(restquest);
            Newtonsoft.Json.Linq.JObject token = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(responsedata);
            if (token["access_token"] != null) { 
            token_v2 = token["access_token"].ToString();
            token_date = DateTime.Now;
            txtLog.AppendText("\r\n Call:GetTokenV2 \r\n result:" + token_v2);
                fromOrgId = false;
            }
            else
            {
                txtLog.AppendText("\r\n Call:GetTokenV2 \r\n result:" + responsedata);
            }
        }
        /// <summary>
        /// 对密码进行加密
        /// </summary>
        /// <param name="password"></param>
        public void EncryptPass(ref string password)
        {
            UTF8Encoding encode = new UTF8Encoding();
            Byte[] hashByte = new byte[] { };

            //if (password.Length == 32)//支持前端md5的密码。
            //{
            //    hashByte = Ufida.T.EAP.Aop.Util.SpereTool.ConvertHexToBytes(password.ToUpper());
            //}
            //else
            {
                System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

                hashByte = md5.ComputeHash(encode.GetBytes(password));
            }

            password = Convert.ToBase64String(hashByte);
        }

        public string EncodeMD5(string str)
        {
            UTF8Encoding encode = new UTF8Encoding();
            Byte[] hashByte = new byte[] { };

            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            hashByte = md5.ComputeHash(encode.GetBytes(str));

            return Ufida.T.EAP.Aop.Util.SpereTool.ConvertBytesToHex(hashByte, false);
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F2 && e.Modifiers == Keys.Control)
            {
                this.btnOthFeatures.Visible = true;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdChoice = new OpenFileDialog();
            ofdChoice.Title = "打开私钥文件";
            ofdChoice.Filter = "EXCEL文件(*.pem;*.pem)|*.pem;*.pem";
            ofdChoice.RestoreDirectory = true;
            DataTable dt = new DataTable();
            if (ofdChoice.ShowDialog() == DialogResult.OK)
            {
                //打开文件对话框选择的文件
                string strExcelPath = ofdChoice.FileName;
                txtPriKeyPath.Text = strExcelPath;
            }
        }

        private bool IsCircle = false;
        private void btn_circle_Click(object sender, EventArgs e)
        {
            IsCircle = true;
            db.GetConnection();
            Thread dataThread = new Thread(delegate ()
            {
                while (true)
                {

                    DataTable dt =  db.GetDataSet(@"SELECT   AutoID, TaskType, TaskTypeName, TaskNumber, ProjectName, ProjectDesc, XcNumber, Sl, TaskSubType, 
                TaskSubTypeName, InputRq, TargetWareHouseID, TargetWareHouseName, TargetWareRoomID, 
                TargetWareRoomName, Ymbatch, IsSynchro, materialarea, mjtotal, ptunitname, secondunitname, producttype, 
                productsubtype,CreateManID, 
                CreateMan, CreateRq, UpdateManID, UpdateMan, UpdateRq
FROM      Sta_TaskWork_D
WHERE   (TaskType = 'IM') AND (TaskSubType IN ('IM2005', 'IM1008')) and IsSynchro=0 ", "test");
                    if (dt.Rows.Count > 0&& IsCircle)
                    {
                        for(int i=0;i<dt.Rows.Count;i++)
                        {
                            //this.txtArgs.Text = dt.Rows[i]["AutoID"].ToString()+"-"+dt.Rows[i]["CreateRq"].ToString()+"-"+ dt.Rows[i]["ProjectName"].ToString()+ "-" +dt.Rows[i]["Sl"].ToString() ;
                            string sendtext = "";
                            try
                            {
                                string busi = "03";
                                string num = Math.Round((Convert.ToDecimal(dt.Rows[i]["Sl"].ToString()) * Convert.ToDecimal(dt.Rows[i]["materialarea"].ToString())),5).ToString();
                               // string area = dt.Rows[i]["materialarea"].ToString();
                                if (Convert.ToInt32(dt.Rows[i]["Sl"])<0)
                                {
                                    busi = "04";
                                    //num = Math.Abs(Convert.ToInt32(dt.Rows[i]["Sl"])).ToString();
                                }
                                sendtext = "{\"dto\" : {\"ExternalCode\" : \"" + dt.Rows[i]["AutoID"].ToString() + "\",\"Code\" : \"1001\",\"VoucherType\" :{\"Code\" : \"ST1002\"},\"Partner\" : {\"Code\" : \"001\"},\"VoucherDate\" : \""+ Convert.ToDateTime(dt.Rows[i]["CreateRq"].ToString()).ToString("yyyy-MM-dd") + "\",\"BusiType\" : {\"Code\" :\"" + busi+" \"  },\"Warehouse\" : {\"Code\" : \"002\"},\"Memo\" : \"接口导入\",\"RDRecordDetails\" : [{\"Code\" : \"0001\",\"Inventory\" : {\"Code\" : \"" + dt.Rows[i]["ProjectName"].ToString() + "\"},\"BaseQuantity\" : " + num + ",\"Amount\" : 0,\"Price\" : 0     }]}}";
                                this.txtArgs.Text = sendtext;

                            }
                            catch (Exception ex)
                            {
                                this.txtArgs.Text = ex.ToString(); ;
                            }


                            if (!isLogined())
                            {
                                try
                                {
                                    TPlusAPI.Logout();
                                }
                                catch(Exception ex)
                                {
                                    txtLog.AppendText("\r\n\r\n Logout:");
                                    txtLog.AppendText("\r\n error:" + ex.Message + "\r\n");
                                }
                                this.btnGetToken_Click(sender, e);
                            }


                            try
                            {
                                string result = this.TPlusAPI.Call<string>("productReceive/Create", sendtext);
                                if(result==""||result == "null" || result ==null)
                                {
                                    db.ExecScalar("update Sta_TaskWork_D set IsSynchro=1,UpdateRq=getdate(),UpdateMan='系统导入' where AutoID=" + dt.Rows[i]["AutoID"].ToString() + " ");
                                }
                                else
                                {
                                    if (result.IndexOf("EXSM0003")>=0)
                                    {
                                        this.btnReLogin_Click(sender, e);
                                    }
                                }
                                //dynamic result = this.TPlusAPI.Call(txtResourceName.Text, txtArgs.Text);

                                txtLog.AppendText("\r\n\r\n call:" + txtResourceName.Text);
                                txtLog.AppendText("\r\n result:" + result);
                            }
                            catch (RestException ex)
                            {
                                txtLog.AppendText("\r\n\r\n call:" + txtResourceName.Text);
                                txtLog.AppendText("\r\n error:" + ex.Message + "\r\n" + ex.ResponseBody);

                                if (ex.ResponseBody.IndexOf("EXSM0003") >= 0)
                                {
                                    this.btnReLogin_Click(sender, e);
                                }
                            }
                        }

                       
                    }
                    
                    Thread.Sleep(Convert.ToInt32(this.txt_IntervalTime.Text));
                   
                }

            });
            dataThread.IsBackground = true;
            dataThread.Name = "123";
            dataThread.Start();
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            IsCircle = false;
            this.V2_Test.Enabled = true;
        }
        private bool IsClick = false;  //阻住多次点击,标识全局第一次点击
        private void V2_Test_Click(object sender, EventArgs e)
        {
            if(IsClick == false)
            {
                IsClick = true;
                this.V2_Test.Enabled = false;
            }
            else
            {
                IsCircle = true;
                this.V2_Test.Enabled = false;
                return;
            }
            try
            {
                IsCircle = true;
                //登录获取token
                this.btnV2LoginWithUserPwd_Click(sender, e);
                //return;
                db.GetConnection();
                Thread dataThread = new Thread(delegate () { 
                    while(true)
                    {
                        if (IsCircle)
                        {
                            //成品接口
                            DataTable dt = db.GetDataSet(@"SELECT top 1   AutoID, TaskType, TaskTypeName, TaskNumber, ProjectName, ProjectDesc, XcNumber, Sl, TaskSubType, 
                TaskSubTypeName, InputRq, TargetWareHouseID, TargetWareHouseName, TargetWareRoomID, 
                TargetWareRoomName, Ymbatch, IsSynchro, materialarea, mjtotal, ptunitname, secondunitname, producttype, 
                productsubtype,CreateManID, 
                CreateMan, CreateRq, UpdateManID, UpdateMan, UpdateRq
FROM      Sta_TaskWork_D
WHERE   (TaskType = 'IM') AND (TaskSubType IN ('IM2005', 'IM1008')) and IsSynchro=0 ", "t1");

                            if (dt.Rows.Count > 0)
                            {
                                if (token_date.AddMinutes(29) < DateTime.Now)  //用友的时间是30分钟过期，为了防止时间差判断29分钟
                                {
                                    this.btnV2LoginWithUserPwd_Click(sender, e);
                                }
                                string appkey = this.txtAppKey.Text.Trim();
                                string appsecret = this.txtAppSecret.Text.Trim();
                                string orgid = this.textBoxOrgId.Text.Trim();
                                //业务请求的Authorization
                                var customParas = new Dictionary<string, object>
                                                {
                                                    {"access_token", token_v2},

                                                };
                                //默认规则是当前参数+appsecret，组成签名的原值
                                var bizheader = new Dictionary<string, object>
                                                {
                                                    {"appkey", appkey},
                                                    {"orgid",fromOrgId?orgid:string.Empty},
                                                    {"appsecret", appsecret}
                                                };
                                string privateKeyPath = this.txtPriKeyPath.Text.Trim();
                                if (string.IsNullOrEmpty(privateKeyPath) || !File.Exists(privateKeyPath))
                                {
                                    MessageBox.Show("请指定私钥路径！");
                                }

                                RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
                                string bizdatas = jsonSerializer.Serialize(bizheader);
                                Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();
                                string bizAuthorization = tokenManage.CreateSignedToken(bizdatas, privateKeyPath, customParas);
                                ITRestRequest restquest1 = new TRestRequest();
                                restquest1.Method = TMethod.POST;
                                string serverUrl = this.cmServerURL.Text.Trim();
                                string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2) + 1);

                                restquest1.Resource = serverUrl.Replace(host, "") + "productReceive/Create";

                                string authStr1 = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + bizAuthorization + @""",""orgId"":" + (fromOrgId ? orgid : @"""""") + @"}";

                                string encode1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr1));

                                restquest1.AddParameter("Authorization", encode1, TParameterType.HttpHeader);



                                string sendtext = "";
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    try
                                    {
                                        //int i = 0;
                                        string busi = "03";
                                        string num = Math.Round((Convert.ToDecimal(dt.Rows[i]["Sl"].ToString()) * Convert.ToDecimal(dt.Rows[i]["materialarea"].ToString())), 5).ToString();
                                        // string area = dt.Rows[i]["materialarea"].ToString();
                                        if (Convert.ToInt32(dt.Rows[i]["Sl"]) < 0)
                                        {
                                            busi = "04";
                                            //num = Math.Abs(Convert.ToInt32(dt.Rows[i]["Sl"])).ToString();
                                        }
                                        sendtext = "{\"dto\" : {\"ExternalCode\" : \"" + dt.Rows[i]["AutoID"].ToString() + "\",\"Code\" : \"1001\",\"VoucherType\" :{\"Code\" : \"ST1002\"},\"Partner\" : {\"Code\" : \"001\"},\"VoucherDate\" : \"" + Convert.ToDateTime(dt.Rows[i]["InputRq"].ToString()).ToString("yyyy-MM-dd") + "\",\"BusiType\" : {\"Code\" :\"" + busi + "\"  },\"Warehouse\" : {\"Code\" : \"002\"},\"Memo\" : \"接口导入\",\"RDRecordDetails\" : [{\"Code\" : \"0001\",\"Inventory\" : {\"Code\" : \"" + dt.Rows[i]["ProjectName"].ToString() + "\"},\"BaseQuantity\" : " + num + ",\"Amount\" : 0,\"Price\" : 0     }]}}";
                                        //this.txtArgs.Text = sendtext;

                                    }
                                    catch (Exception ex)
                                    {
                                        this.txtArgs.Text = ex.ToString(); ;
                                    }

                                    string args = sendtext;
                                    restquest1.AddParameter("_args", args);
                                    TRestClient restclient = new TRestClient(host);
                                    string responsedata1 = restclient.Execute(restquest1);
                                    if (responsedata1 == "" || responsedata1 == "null" || responsedata1 == null)
                                    {
                                        db.ExecScalar("update Sta_TaskWork_D set IsSynchro=1,UpdateRq=getdate(),UpdateMan='系统导入',IssyncErrorDesc='同步成功' where AutoID=" + dt.Rows[i]["AutoID"].ToString() + " ");

                                        txtLog.Text = "导入成功";
                                    }
                                    else
                                    {
                                        try
                                        {
                                            db.ExecScalar("update Sta_TaskWork_D set IsSynchro=2,UpdateRq=getdate(),UpdateMan='系统导入',IssyncErrorDesc='" + responsedata1.Replace('\'', '\"') + "' where AutoID=" + dt.Rows[i]["AutoID"].ToString() + " ");
                                            txtLog.Text = "";
                                            txtLog.AppendText("\r\n\r\n call:resultend");
                                            txtLog.AppendText("\r\n result:" + responsedata1);
                                            txtLog.AppendText("\r\n 报文:" + sendtext);
                                        }
                                        catch (Exception ex)
                                        {
                                            txtArgs.Text = ex.ToString();
                                        }
                                    }
                                   
                                }
                            }
                            //存货创建
                            DataTable dt2 = db.GetDataSet(@" SELECT top 1  autoID,projectname,projectdesc, SpecificationModel, SecondUnitName, FnComu3, IsSynchro,MaterialTypeID,ptunitname,convertratio  
                                                                FROM F_YmSoft_PtManage where (MaterialTypeID IN ('101', '102','301','302'))  and IsSynchro=0", "t2");
                            if(dt2.Rows.Count>0)
                            {
                                if (token_date.AddMinutes(29) < DateTime.Now)  //用友的时间是30分钟过期，为了防止时间差判断29分钟
                                {
                                    this.btnV2LoginWithUserPwd_Click(sender, e);
                                }
                                string appkey = this.txtAppKey.Text.Trim();
                                string appsecret = this.txtAppSecret.Text.Trim();
                                string orgid = this.textBoxOrgId.Text.Trim();
                                //业务请求的Authorization
                                var customParas = new Dictionary<string, object>
                                                {
                                                    {"access_token", token_v2},

                                                };
                                //默认规则是当前参数+appsecret，组成签名的原值
                                var bizheader = new Dictionary<string, object>
                                                {
                                                    {"appkey", appkey},
                                                    {"orgid",fromOrgId?orgid:string.Empty},
                                                    {"appsecret", appsecret}
                                                };
                                string privateKeyPath = this.txtPriKeyPath.Text.Trim();
                                if (string.IsNullOrEmpty(privateKeyPath) || !File.Exists(privateKeyPath))
                                {
                                    MessageBox.Show("请指定私钥路径！");
                                }

                                RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
                                string bizdatas = jsonSerializer.Serialize(bizheader);
                                Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();
                                string bizAuthorization = tokenManage.CreateSignedToken(bizdatas, privateKeyPath, customParas);
                                ITRestRequest restquest1 = new TRestRequest();
                                restquest1.Method = TMethod.POST;
                                string serverUrl = this.cmServerURL.Text.Trim();
                                string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2) + 1);

                                restquest1.Resource = serverUrl.Replace(host, "") + "inventory/Create";

                                string authStr1 = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + bizAuthorization + @""",""orgId"":" + (fromOrgId ? orgid : @"""""") + @"}";

                                string encode1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr1));

                                restquest1.AddParameter("Authorization", encode1, TParameterType.HttpHeader);



                                string sendtext = "";
                                try
                                {
                                    string Code = "";
                                    if (dt2.Rows[0]["MaterialTypeID"].ToString() == "101" || dt2.Rows[0]["MaterialTypeID"].ToString() == "102")
                                    {
                                        Code = "A1";
                                    }
                                    if (dt2.Rows[0]["MaterialTypeID"].ToString() == "301")
                                    {
                                        Code = "A";
                                    }
                                    if (dt2.Rows[0]["MaterialTypeID"].ToString() == "302")
                                    {
                                        Code = "B";
                                    }
                                    Inventory model = new Inventory();
                                    model.Code = dt2.Rows[0][1].ToString();
                                    model.Name = dt2.Rows[0][2].ToString();
                                    model.Shorthand = "";
                                    model.Specification = dt2.Rows[0][3].ToString();
                                    model.DefaultBarCode = "";
                                    model.InventoryClass = new BaseModel1() { Code = Code };
                                    model.Disabled = "false";
                                    model.IsPurchase = "true";
                                    model.IsSale = "true";
                                    model.IsMadeSelf = "true";
                                    model.IsMaterial = "true";
                                    model.IsSuite = "false";
                                    model.IsLaborCost = "false";



                                    model.Unit = new BaseModel3() {  Name = dt2.Rows[0]["ptunitname"].ToString() };
                                    model.UnitByPurchase= new BaseModel3() {  Name = dt2.Rows[0]["ptunitname"].ToString() };
                                    model.UnitBySale = new BaseModel3() { Name = dt2.Rows[0]["ptunitname"].ToString() };
                                    model.UnitByRetail = new BaseModel3() { Name = dt2.Rows[0]["ptunitname"].ToString() };
                                    model.UnitByStock = new BaseModel3() { Name = dt2.Rows[0]["ptunitname"].ToString() };
                                    model.UnitByManufacture = new BaseModel3() { Name = dt2.Rows[0]["ptunitname"].ToString() };
                                    model.SubUnitByReport = new BaseModel3() { Name = dt2.Rows[0]["ptunitname"].ToString() };

                                    model.IsSingleUnit = false;

                                    model.UnitType = new BaseModel1() { Code="01"};
                                    model.UnitGroup = new BaseModel3() { Name = dt2.Rows[0]["ptunitname"].ToString()+"/"+dt2.Rows[0]["SecondUnitName"].ToString() };
                                    model.ValueType = new BaseModel1() { Code = "01" };
                                    InvUnitPriceDTO PriceDto = new InvUnitPriceDTO();
                                    PriceDto.Unit = new BaseModel3() { Name = dt2.Rows[0]["ptunitname"].ToString() };
                                    PriceDto.rateOfExchange = dt2.Rows[0]["convertratio"].ToString();
                                    model.InvUnitPriceDTOs = new List<InvUnitPriceDTO>() { PriceDto };

                                    InventoryDTO result = new InventoryDTO() { dto = model };
                                    sendtext = JsonConvert.SerializeObject(result);

                                }
                                catch(Exception ex)
                                {
                                    this.txtArgs.Text = ex.ToString(); ;
                                }

                                string args = sendtext;
                                restquest1.AddParameter("_args", args);
                                TRestClient restclient = new TRestClient(host);
                                string responsedata1 = restclient.Execute(restquest1);
                                if (responsedata1 == "" || responsedata1 == "null" || responsedata1 == null)
                                {

                                    try
                                    {
                                        db.ExecScalar("update F_YmSoft_PtManage set IsSynchro=1,ModifyRq=getdate(),ModifyMan='系统导入',IssyncErrorDesc='同步成功' where AutoID=" + dt2.Rows[0]["AutoID"].ToString() + " ");

                                        txtStock.Text = "导入成功";
                                    }
                                    catch(Exception ex)
                                    {
                                        txtArgs.Text = ex.ToString();
                                    }
    
                                }
                                else
                                {
                                    try
                                    {
                                        db.ExecScalar("update F_YmSoft_PtManage set IsSynchro=2,ModifyRq=getdate(),ModifyMan='系统导入',IssyncErrorDesc='" + responsedata1.Replace('\'', '\"') + "' where AutoID=" + dt2.Rows[0]["AutoID"].ToString() + " ");
                                        txtStock.Text = "";
                                        txtStock.AppendText("\r\n\r\n call:resultend");
                                        txtStock.AppendText("\r\n result:" + responsedata1);
                                        txtStock.AppendText("\r\n 报文:" + sendtext);
                                    }
                                    catch(Exception ex)
                                    {
                                        txtArgs.Text = ex.ToString();
                                    }
                                }
                            }

                            //材料出库
                            if (this.cbInterface2.Checked)
                            {
                                DataTable dt3 = db.GetDataSet(@" SELECT top 1 AutoID, ProjectName, InputRq, Sl, TotalSl,IsSynchro,TaskSubType,Ymbatch   
                                                            FROM  Sta_InvWork_D WHERE     (TaskSubType IN ('X10108S', 
                                                            'X10109S', 'X20108S','X10108F', 
                                                            'X10109F', 'X20108F'))  and IsSynchro=0 ", "t3");
                                if (dt3.Rows.Count > 0)
                                {
                                    if (token_date.AddMinutes(29) < DateTime.Now)  //用友的时间是30分钟过期，为了防止时间差判断29分钟
                                    {
                                        this.btnV2LoginWithUserPwd_Click(sender, e);
                                    }
                                    string appkey = this.txtAppKey.Text.Trim();
                                    string appsecret = this.txtAppSecret.Text.Trim();
                                    string orgid = this.textBoxOrgId.Text.Trim();
                                    //业务请求的Authorization
                                    var customParas = new Dictionary<string, object>
                                                {
                                                    {"access_token", token_v2},

                                                };
                                    //默认规则是当前参数+appsecret，组成签名的原值
                                    var bizheader = new Dictionary<string, object>
                                                {
                                                    {"appkey", appkey},
                                                    {"orgid",fromOrgId?orgid:string.Empty},
                                                    {"appsecret", appsecret}
                                                };
                                    string privateKeyPath = this.txtPriKeyPath.Text.Trim();
                                    if (string.IsNullOrEmpty(privateKeyPath) || !File.Exists(privateKeyPath))
                                    {
                                        MessageBox.Show("请指定私钥路径！");
                                    }

                                    RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
                                    string bizdatas = jsonSerializer.Serialize(bizheader);
                                    Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();
                                    string bizAuthorization = tokenManage.CreateSignedToken(bizdatas, privateKeyPath, customParas);
                                    ITRestRequest restquest1 = new TRestRequest();
                                    restquest1.Method = TMethod.POST;
                                    string serverUrl = this.cmServerURL.Text.Trim();
                                    string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2) + 1);

                                    restquest1.Resource = serverUrl.Replace(host, "") + "materialDispatch/Create";

                                    string authStr1 = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + bizAuthorization + @""",""orgId"":" + (fromOrgId ? orgid : @"""""") + @"}";

                                    string encode1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr1));

                                    restquest1.AddParameter("Authorization", encode1, TParameterType.HttpHeader);



                                    string sendtext = "";
                                    try
                                    {
                                        string Code = "";
                                        if (dt3.Rows[0]["TaskSubType"].ToString() == "X10108S" || dt3.Rows[0]["TaskSubType"].ToString() == "X10109S" || dt3.Rows[0]["TaskSubType"].ToString() == "X20108S")
                                        {
                                            Code = "41";
                                        }
                                        if (dt3.Rows[0]["TaskSubType"].ToString() == "X10108F" || dt3.Rows[0]["TaskSubType"].ToString() == "X10109F" || dt3.Rows[0]["TaskSubType"].ToString() == "X20108F")
                                        {
                                            Code = "42";
                                        }
                                        MaterialDispatch model = new MaterialDispatch();
                                        model.ExternalCode = dt3.Rows[0]["AutoID"].ToString();
                                        model.code = "1001";
                                        model.VoucherType = new BaseModel1 { Code = "ST1022" };
                                        model.Partner = new BaseModel1 { Code = "001" };
                                        model.VoucherDate = dt3.Rows[0]["InputRq"].ToString();
                                        model.BusiType = new BaseModel1() { Code = Code };
                                        model.Warehouse = new BaseModel1() { Code = "001" }; ;
                                        model.Memo = "";


                                        MaterialDispatchDetail detailmodel = new MaterialDispatchDetail();
                                        detailmodel.Code = "0001";
                                        detailmodel.Inventory = new BaseModel1() { Code = dt3.Rows[0]["ProjectName"].ToString() };

                                        detailmodel.BaseQuantity = Convert.ToDecimal(dt3.Rows[0]["TotalSl"].ToString());
                                        if (Code == "42")
                                        {
                                            detailmodel.BaseQuantity = detailmodel.BaseQuantity * -1;
                                        }
                                        detailmodel.Batch = dt3.Rows[0]["Ymbatch"].ToString();
                                        model.RDRecordDetails = new List<MaterialDispatchDetail>() { detailmodel };
                                        MaterialDispatchDTO result = new MaterialDispatchDTO() { dto = model };
                                        sendtext = JsonConvert.SerializeObject(result);

                                    }
                                    catch (Exception ex)
                                    {
                                        this.txtArgs.Text = ex.ToString(); ;
                                    }

                                    string args = sendtext;
                                    restquest1.AddParameter("_args", args);
                                    TRestClient restclient = new TRestClient(host);
                                    string responsedata1 = restclient.Execute(restquest1);
                                    if (responsedata1 == "" || responsedata1 == "null" || responsedata1 == null)
                                    {
                                        try
                                        {
                                            db.ExecScalar("update Sta_InvWork_D set IsSynchro=1,UpdateRq=getdate(),UpdateMan='系统导入',IssyncErrorDesc='同步成功' where AutoID=" + dt3.Rows[0]["AutoID"].ToString() + " ");

                                            txtMOut.Text = "导入成功";
                                        }
                                        catch (Exception ex)
                                        {
                                            txtArgs.Text = ex.ToString();
                                        }

                                    }
                                    else
                                    {
                                        try
                                        {
                                            db.ExecScalar("update Sta_InvWork_D set IsSynchro=2,UpdateRq=getdate(),UpdateMan='系统导入',IssyncErrorDesc='" + responsedata1.Replace('\'', '\"') + "' where AutoID=" + dt3.Rows[0]["AutoID"].ToString() + " ");
                                            txtMOut.Text = "";
                                            txtMOut.AppendText("\r\n\r\n call:resultend");
                                            txtMOut.AppendText("\r\n result:" + responsedata1);
                                            txtMOut.AppendText("\r\n 报文:" + sendtext);
                                        }
                                        catch (Exception ex)
                                        {
                                            txtArgs.Text = ex.ToString();
                                        }
                                    }
                                }
                            }

                            //其他出库
                            if (this.cbInterface3.Checked)
                            {
                                DataTable dt4 = db.GetDataSet(@"SELECT top 1  AutoID, ProjectName, InputRq, Sl, TotalSl, IsSynchro,TaskSubType 
                                            FROM  Sta_InvWork_D WHERE (TaskSubType IN ('X20120S', 'X10120S','X20120F', 'X10120F'))　and IsSynchro=0", "t4");
                                if (dt4.Rows.Count > 0)
                                {
                                    if (token_date.AddMinutes(29) < DateTime.Now)  //用友的时间是30分钟过期，为了防止时间差判断29分钟
                                    {
                                        this.btnV2LoginWithUserPwd_Click(sender, e);
                                    }
                                    string appkey = this.txtAppKey.Text.Trim();
                                    string appsecret = this.txtAppSecret.Text.Trim();
                                    string orgid = this.textBoxOrgId.Text.Trim();
                                    //业务请求的Authorization
                                    var customParas = new Dictionary<string, object>
                                                {
                                                    {"access_token", token_v2},

                                                };
                                    //默认规则是当前参数+appsecret，组成签名的原值
                                    var bizheader = new Dictionary<string, object>
                                                {
                                                    {"appkey", appkey},
                                                    {"orgid",fromOrgId?orgid:string.Empty},
                                                    {"appsecret", appsecret}
                                                };
                                    string privateKeyPath = this.txtPriKeyPath.Text.Trim();
                                    if (string.IsNullOrEmpty(privateKeyPath) || !File.Exists(privateKeyPath))
                                    {
                                        MessageBox.Show("请指定私钥路径！");
                                    }

                                    RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
                                    string bizdatas = jsonSerializer.Serialize(bizheader);
                                    Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();
                                    string bizAuthorization = tokenManage.CreateSignedToken(bizdatas, privateKeyPath, customParas);
                                    ITRestRequest restquest1 = new TRestRequest();
                                    restquest1.Method = TMethod.POST;
                                    string serverUrl = this.cmServerURL.Text.Trim();
                                    string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2) + 1);

                                    restquest1.Resource = serverUrl.Replace(host, "") + "otherDispatch/Create";

                                    string authStr1 = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + bizAuthorization + @""",""orgId"":" + (fromOrgId ? orgid : @"""""") + @"}";

                                    string encode1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr1));

                                    restquest1.AddParameter("Authorization", encode1, TParameterType.HttpHeader);



                                    string sendtext = "";
                                    try
                                    {
                                        string Code = "";
                                        if (dt4.Rows[0]["TaskSubType"].ToString() == "X20120S" || dt4.Rows[0]["TaskSubType"].ToString() == "X10120S")
                                        {
                                            Code = "13";
                                        }
                                        if (dt4.Rows[0]["TaskSubType"].ToString() == "X20120F" || dt4.Rows[0]["TaskSubType"].ToString() == "X10120F")
                                        {
                                            Code = "14";
                                        }
                                        OtherDispatch model = new OtherDispatch();
                                        model.ExternalCode = dt4.Rows[0]["AutoID"].ToString();
                                        model.VoucherType = new BaseModel1 { Code = "ST1024" };
                                        model.VoucherDate = dt4.Rows[0]["InputRq"].ToString();
                                        model.BusiType = new BaseModel1() { Code = Code };
                                        model.RdStyle = new BaseModel1() { Code = "202" };
                                        model.Warehouse = new BaseModel1() { Code = "003" }; ;


                                        OtherDispatchDetail detailmodel = new OtherDispatchDetail();
                                        detailmodel.Inventory = new BaseModel1() { Code = dt4.Rows[0]["ProjectName"].ToString() };
                                        detailmodel.BaseQuantity = Convert.ToDecimal(dt4.Rows[0]["TotalSl"].ToString());
                                        if (Code == "14")
                                        {
                                            detailmodel.BaseQuantity = detailmodel.BaseQuantity * -1;
                                        }
                                        model.RDRecordDetails = new List<OtherDispatchDetail>() { detailmodel };
                                        OtherDispatchDto result = new OtherDispatchDto() { dto = model };
                                        sendtext = JsonConvert.SerializeObject(result);

                                    }
                                    catch (Exception ex)
                                    {
                                        this.txtArgs.Text = ex.ToString(); ;
                                    }

                                    string args = sendtext;
                                    restquest1.AddParameter("_args", args);
                                    TRestClient restclient = new TRestClient(host);
                                    string responsedata1 = restclient.Execute(restquest1);
                                    if (responsedata1 == "" || responsedata1 == "null" || responsedata1 == null)
                                    {
                                        try
                                        {
                                            db.ExecScalar("update Sta_InvWork_D set IsSynchro=1,UpdateRq=getdate(),UpdateMan='系统导入',IssyncErrorDesc='同步成功' where AutoID=" + dt4.Rows[0]["AutoID"].ToString() + " ");

                                            txtOtherOut.Text = "导入成功";
                                        }
                                        catch (Exception ex)
                                        {
                                            txtArgs.Text = ex.ToString();
                                        }

                                    }
                                    else
                                    {

                                        try
                                        {
                                            db.ExecScalar("update Sta_InvWork_D set IsSynchro=2,UpdateRq=getdate(),UpdateMan='系统导入',IssyncErrorDesc='" + responsedata1.Replace('\'', '\"') + "' where AutoID=" + dt4.Rows[0]["AutoID"].ToString() + " ");
                                            txtOtherOut.Text = "";
                                            txtOtherOut.AppendText("\r\n\r\n call:resultend");
                                            txtOtherOut.AppendText("\r\n result:" + responsedata1);
                                            txtOtherOut.AppendText("\r\n 报文:" + sendtext);
                                        }
                                        catch (Exception ex)
                                        {
                                            txtArgs.Text = ex.ToString();
                                        }
                                    }
                                }
                            }
                        }
                        Thread.Sleep(Convert.ToInt32(this.txt_IntervalTime.Text));
                    }
                });

                dataThread.IsBackground = true;
                dataThread.Name = "数据同步后台线程";
                dataThread.Start();
            }
            catch (Exception ex)
            {
                txtLog.AppendText("\r\n\r\n call:" + txtResourceName.Text);
                txtLog.AppendText("\r\n error:" + ex.Message);
            }
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (token_date.AddMinutes(29) < DateTime.Now)  //用友的时间是30分钟过期，为了防止时间差判断29分钟
            {
                this.btnV2LoginWithUserPwd_Click(sender, e);
            }
            string appkey = this.txtAppKey.Text.Trim();
            string appsecret = this.txtAppSecret.Text.Trim();
            string orgid = this.textBoxOrgId.Text.Trim();
            //业务请求的Authorization
            var customParas = new Dictionary<string, object>
                                                {
                                                    {"access_token", token_v2},

                                                };
            //默认规则是当前参数+appsecret，组成签名的原值
            var bizheader = new Dictionary<string, object>
                                                {
                                                    {"appkey", appkey},
                                                    {"orgid",fromOrgId?orgid:string.Empty},
                                                    {"appsecret", appsecret}
                                                };
            string privateKeyPath = this.txtPriKeyPath.Text.Trim();
            if (string.IsNullOrEmpty(privateKeyPath) || !File.Exists(privateKeyPath))
            {
                MessageBox.Show("请指定私钥路径！");
            }

            RestSharp.Serializers.JsonSerializer jsonSerializer = new RestSharp.Serializers.JsonSerializer();
            string bizdatas = jsonSerializer.Serialize(bizheader);
            Ufida.T.EAP.Net.security.TokenManage tokenManage = new Ufida.T.EAP.Net.security.TokenManage();
            string bizAuthorization = tokenManage.CreateSignedToken(bizdatas, privateKeyPath, customParas);
            ITRestRequest restquest1 = new TRestRequest();
            restquest1.Method = TMethod.POST;
            string serverUrl = this.cmServerURL.Text.Trim();
            string host = serverUrl.Substring(0, serverUrl.IndexOf('/', serverUrl.IndexOf("//") + 2) + 1);

            restquest1.Resource = serverUrl.Replace(host, "") + "ProductReceiveOpenApi/GetVoucherDTO";

            string authStr1 = @"{""appKey"":""" + appkey + @""",""authInfo"":""" + bizAuthorization + @""",""orgId"":" + (fromOrgId ? orgid : @"""""") + @"}";

            string encode1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authStr1));

            restquest1.AddParameter("Authorization", encode1, TParameterType.HttpHeader);



            string sendtext = "";
            try
            {
                string Code = "";

                SearchModel model = new SearchModel();
                model.voucherCode = this.txtyongyouNo.Text;



                SendModel result = new SendModel() { param = model };
                sendtext = JsonConvert.SerializeObject(result);

            }
            catch (Exception ex)
            {
                this.txtArgs.Text = ex.ToString(); ;
            }

            string args = sendtext;
            restquest1.AddParameter("_args", args);
            TRestClient restclient = new TRestClient(host);
            string responsedata1 = restclient.Execute(restquest1);
            txtOtherOut.Text = "";
            txtOtherOut.AppendText("\r\n\r\n call:resultend");
            txtOtherOut.AppendText("\r\n result:" + responsedata1);
            txtOtherOut.AppendText("\r\n 报文:" + sendtext);
        }
    }
}
